<script setup lang="ts">
import jsonData from "#/index.json"
import { onMounted, reactive, ref, watch } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { RefreshRight } from "@element-plus/icons-vue"

import { getPositionInformation, aduitPosition } from "@/api/position"
import { PositionDetails, QueryPositionFormParams } from "@/api/position/type"
import { cloneDeep } from "lodash-es"
import { addressCascaderOpts, getAddressDetails, transformAddressToString } from "@/utils/transform"
import { usePagination } from "@/hooks/usePagination"

// #region 审批岗位
const dialogVisiable = ref(false)
const descriptionData = reactive({
  position: {
    createTime: "",
    id: "",
    studyingExperience: undefined as any,
    updateTime: "",
    workAddress: [] as [(string | number)?, (string | number)?, (string | number)?],
    workDescription: "",
    workPrice: undefined as any,
    workTime: undefined as any,
    workName: "",
    workStatus: undefined as any
  },
  company: {
    companyAddress: [] as [number?, number?, number?],
    companyDescription: "",
    companyEmail: "",
    companyName: "",
    companyPhone: "",
    companyPictures: [] as string[],
    companyRegisterCapital: "",
    companyRegisterDate: "",
    companyShortName: ""
  }
})
const activeDescriptionTab = ref("position")

function resetDescriptionData() {
  activeDescriptionTab.value = "position"
}

function handleAduitPosition(status: boolean) {
  const params = {
    id: Number(descriptionData.position?.id),
    workStatus: (status ? 2 : 1) as 1 | 2
  }
  aduitPosition(params).then(() => {
    dialogVisiable.value = false
    ElMessage({ type: "success", message: "操作成功" })
  })
}

function handleOpenAuditDialog(data: PositionDetails) {
  dialogVisiable.value = true
  const { companyVO, ...positionVO } = data
  descriptionData.position = cloneDeep(positionVO)
  descriptionData.company = cloneDeep(companyVO)
}
// #endregion

// #region 查询岗位
const DEFAULT_SEARCH_PARAMS: QueryPositionFormParams = {
  studyingExperience: undefined,
  workAddress: [],
  workPrice: undefined,
  workName: "",
  workTime: undefined
}
const cascaderOpts = ref()
const searchFormRef = ref<FormInstance | null>()
const searchFormData = ref(cloneDeep(DEFAULT_SEARCH_PARAMS))
const searchFormRules: FormRules = {
  workName: [{ type: "string" }],
  studyingExperience: [
    {
      trigger: "change",
      validator: (rule, val, cb) => {
        if ([undefined, 0, 1, 2, 3, 4, 5, 6].includes(val)) {
          cb()
        } else {
          cb("请选择正确的学历选项")
        }
      }
    }
  ],
  workTime: [
    {
      trigger: "change",
      validator: (rule, val, cb) => {
        if ([undefined, 0, 1, 2, 3, 4, 5].includes(val)) {
          cb()
        } else {
          cb("请选择正确的工作经验范围")
        }
      }
    }
  ],
  workAddress: [
    {
      type: "array",
      trigger: "change",
      validator: (rule, val, cb) => {
        if (val === undefined || (Array.isArray(val) && [0, 1, 2, 3].includes(val.length))) {
          cb()
        } else {
          cb("您选择的工作区域地址不正确")
        }
      }
    }
  ],
  workMinPrice: [
    {
      type: "number",
      trigger: "blur",
      message: "你输入的期望最少工资不正确"
    }
  ],
  workMaxPrice: [
    {
      type: "number",
      trigger: "blur",
      message: "你输入的期望最多工资不正确"
    }
  ]
}
const { paginationData, handleCurrentChange } = usePagination({
  current: 1,
  layout: "total, prev, pager, next, jumper"
})
const tableData = ref<PositionDetails[]>([])
const getResourecLabel = (val: number, resource: { value: number; label: string }[]) => {
  const [tagItem] = resource.filter((item) => item.value === val)
  return tagItem.label
}

function getPositionData() {
  const paginationParams = {
    current: paginationData.current,
    pageSize: paginationData.pageSize,
    sortOrder: "desc"
  }
  const fixParams = {
    workAddress: transformAddressToString(searchFormData.value.workAddress || [])
  }

  getPositionInformation({ ...searchFormData.value, ...fixParams, ...paginationParams }).then(({ data }) => {
    tableData.value = data.records
    console.log("💬 ⋮ getPositionInformation ⋮ tableData.value => ", tableData.value)
    paginationData.total = Number(data.total)
  })
}

function resetSearch() {
  searchFormRef.value?.resetFields()
  getPositionData()
}

watch(
  () => paginationData.current,
  () => {
    getPositionData()
  }
)

onMounted(() => {
  cascaderOpts.value = addressCascaderOpts
  getPositionData()
})
// #endregion
</script>

<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <el-form ref="searchFormRef" :model="searchFormData" :rules="searchFormRules" :inline="true">
        <el-form-item label="职位名称" prop="workName">
          <el-input v-model="searchFormData.workName" style="width: 170px" placeholder="请输入职位名称" clearable />
        </el-form-item>
        <el-form-item label="学历" prop="studyingExperience">
          <el-select
            v-model="searchFormData.studyingExperience"
            style="width: 130px"
            placeholder="请选择学历"
            clearable
          >
            <el-option
              v-for="{ value, label } in jsonData.studyacademicDegree"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验" prop="workTime">
          <el-select v-model="searchFormData.workTime" style="width: 170px" placeholder="请选择工作经验范围" clearable>
            <el-option v-for="{ value, label } in jsonData.workTime" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作区域" prop="workAddress">
          <el-cascader
            :options="cascaderOpts"
            v-model="searchFormData.workAddress as any"
            style="width: 320px"
            clearable
          />
        </el-form-item>
        <el-form-item label="薪资范围" prop="workPrice">
          <el-select v-model="searchFormData.workPrice" placeholder="请选择薪资范围" style="width: 200px" clearable>
            <el-option v-for="{ label, value } in jsonData.workPrice" :key="value" :value="value" :label="label" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getPositionData()">筛选</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getPositionData()" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column prop="id" label="ID" align="center" width="70" />
          <el-table-column prop="workName" label="职位名称" width="200" align="center" />
          <el-table-column prop="workTime" label="工作经验要求" align="center">
            <template #default="scope">
              <el-tag>{{ getResourecLabel(scope.row.workTime, jsonData.workTime) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="workPrice" label="薪资范围" align="center">
            <template #default="scope">
              <el-tag type="info" size="small" disabled>{{
                getResourecLabel(scope.row.workPrice, jsonData.workPrice)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="studyingExperience" label="学历要求" align="center">
            <template #default="scope">
              <el-tag effect="plain" round>{{
                getResourecLabel(scope.row.studyingExperience, jsonData.studyacademicDegree)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="workAddress" label="工作地址" align="center">
            <template #default="scope">
              <el-text type="info">{{ getAddressDetails(scope.row.workAddress) || "未知" }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="workStatus" label="审核状态" align="center">
            <template #default="scope">
              <el-tag>{{ getResourecLabel(scope.row.workStatus, jsonData.aduit) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
              <el-button plain size="small" @click="handleOpenAuditDialog(scope.row)">职位详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.current"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog v-model="dialogVisiable" @close="resetDescriptionData" width="50%">
      <el-tabs v-model="activeDescriptionTab" type="card">
        <el-tab-pane label="职位信息" name="position">
          <el-descriptions :column="1">
            <el-descriptions-item label="职位名称">
              <el-text type="primary">{{ descriptionData.position?.workName }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item label="工作经验">
              {{ getResourecLabel(descriptionData.position.workTime!, jsonData.workTime) }}</el-descriptions-item
            >
            <el-descriptions-item label="薪资范围">
              <el-tag type="info">{{
                getResourecLabel(descriptionData.position.workPrice!, jsonData.workPrice)
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="职位描述">
              <div style="white-space: pre-line" v-html="descriptionData.position?.workDescription" />
            </el-descriptions-item>
            <el-descriptions-item label="学历">
              <el-tag effect="plain" round>{{
                getResourecLabel(descriptionData.position?.studyingExperience!, jsonData.studyacademicDegree)
              }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="地址">
              <span style="text-decoration: underline dotted">
                <span style="font-size: 14px">{{
                  getAddressDetails(descriptionData.position.workAddress as any) || "未知"
                }}</span>
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ descriptionData.position?.createTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ descriptionData.position?.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="审核状态">
              <el-tag>{{ getResourecLabel(descriptionData.position?.workStatus!, jsonData.aduit) }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="company">
          <el-descriptions :column="1">
            <el-descriptions-item label="公司名称">{{ descriptionData.company.companyName }}</el-descriptions-item>
            <el-descriptions-item label="公司简称">{{ descriptionData.company.companyShortName }}</el-descriptions-item>
            <el-descriptions-item label="公司描述">{{
              descriptionData.company.companyDescription
            }}</el-descriptions-item>
            <el-descriptions-item label="公司电话">{{ descriptionData.company.companyPhone }}</el-descriptions-item>
            <el-descriptions-item label="公司邮箱">{{ descriptionData.company.companyEmail }}</el-descriptions-item>
            <el-descriptions-item label="公司地址">{{ descriptionData.company.companyAddress }}</el-descriptions-item>
            <el-descriptions-item label="公司注册资本">{{
              descriptionData.company.companyRegisterCapital
            }}</el-descriptions-item>
            <el-descriptions-item label="公司注册时间">{{
              descriptionData.company.companyRegisterDate
            }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button
          plain
          round
          :disabled="descriptionData.position?.workStatus === 1"
          @click="handleAduitPosition(false)"
          >审核不通过</el-button
        >
        <el-button
          style="text-align: end"
          type="primary"
          round
          :disabled="descriptionData.position?.workStatus === 2"
          @click="handleAduitPosition(true)"
          >审核通过</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.search-card {
  margin-bottom: 20px;
}
.toolbar-wrapper {
  display: flex;
  flex-flow: row nowrap;
  margin-bottom: 20px;
  justify-content: space-between;
}

.table-wrapper {
  margin-bottom: 20px;
}
</style>
